package com.sixseven.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sixseven.bean.Member;
import com.sixseven.service.MemberService;
import com.sixseven.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Belly
 * @version 1.1.0
 */
@RestController
@Slf4j
public class MemberController {
    @Resource
    private MemberService memberService;
    @PostMapping("/userLogin")
    public Result userLogin(@RequestBody Member member, HttpServletRequest request){
        if (!StringUtils.hasText(member.getUsername())){
            return Result.error();
        }
        if (!StringUtils.hasText(member.getPassword())){
            return Result.error();
        }
        member.setUsername(member.getUsername());
        member.setPassword(member.getPassword());
        Member userLogin = memberService.userLogin(member, request);
        if (userLogin == null){
            return Result.error();
        }
        Result result = Result.success("200", "登录成功");
        result.setData(userLogin);
        return result;
    }
    @PostMapping("/userRegister")
    public Result userRegister(@Validated @RequestBody Member member,
                               Errors errors){
//        log.info("errors={}", errors.getFieldErrors().size());
        Map<String, Object> map = new HashMap<>();
        List<FieldError> fieldErrors = errors.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        if (map.size() != 0){
            return Result.error("533", "注册失败", map);
        }
        int register = memberService.userRegister(member);
        if (register == -2){
            return Result.error("522", "用户名存在", null);
        }
        return register == 1 ? Result.success("200", "注册成功") : Result.error();
    }
    @PostMapping("/userStatus")
    public Result userStatus(HttpServletRequest request){
        Member member = (Member) request.getSession().getAttribute("member");
        if (member == null){
            return Result.error("511", "用户没登陆", null);
        }
        return Result.success(member);
    }
    @RequestMapping("/logout")
    public Result logout(@RequestBody String username, HttpServletRequest request){
//        log.info("username={}", username.isEmpty());
//        log.info("username={}", username);
        if (username.isEmpty()){
            return Result.error();
        }
        Member member = (Member) request.getSession().getAttribute("member");
        if (member == null){
            return Result.error();
        }
        request.getSession().removeAttribute("member");
        return Result.success("200", "成功退出");
    }
    @RequestMapping("/memberList")
    public Result memberList(@RequestParam String searchName,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize){
        LambdaQueryWrapper<Member> memberLambdaQueryWrapper = Wrappers.lambdaQuery();
        memberLambdaQueryWrapper.like(Member::getUsername, searchName);
        Page<Member> memberPage = memberService.page(
                new Page<>(pageNum, pageSize), memberLambdaQueryWrapper);
        if (memberPage == null){
            return Result.error();
        }
        List<Member> records = memberPage.getRecords();
        for (Member record : records) {
            record.setPassword("******");
        }
        return Result.success(memberPage);
    }
    @RequestMapping("/memberStatus")
    public Result memberStatus(@RequestParam Integer memberId, @RequestParam Integer status){
//        log.info("memberId={}", memberId);
//        log.info("status={}", status);
        if (memberId == null){
            return Result.error();
        }
        if (status == null){
            return Result.error();
        }
        Member member = memberService.getById(memberId);
        if (member == null){
            return Result.error();
        }
        member.setStatus(status);
        boolean update = memberService.updateById(member);
        if (!update){
            return Result.error();
        }
        return Result.success("200", "设置成功");
    }
    @DeleteMapping("/delMember/{memberId}")
    public Result delMember(@PathVariable Integer memberId){
        if (memberId == null){
            return Result.error();
        }
        boolean removeById = memberService.removeById(memberId);
        if (removeById){
            return Result.success("200", "删除成功");
        }
        return Result.error();
    }
 }
